/**
 * Created by Ysssssss on 2021/5/26.
 */


import React, { PureComponent } from 'react'
import {withRouter} from "react-router-dom";
import {connect} from "react-redux";

import {
    getShelfProductInfo,
    editShelfProductInfo,
    getShelfGroupList
} from "@sagas/shoppingMall/shoppingMallProduct";
import PageBackHeader from "@common/PageBackHeader";
import {Button, Form, Input, Row, Col, Select} from "antd";
import {exchangeFormDataToFields} from "@utils/exchangeFormData";
import {getHistoryMatchParams} from "@utils/setUrlQuery";
import ShoppingMallProductDetailStandardHandle from "@components/shoppingMall/ShoppingMallProductDetailStandard";
import InputNumberWithSuffix from "@common/presentational/InputNumberWithSuffix";
import getCdnUrl from "@utils/getCdnUrl";


@connect(({ shoppingMallProduct }) => ({
    shelfGroupList: shoppingMallProduct.shelfGroupList,
}), {
    getShelfProductInfo,
    editShelfProductInfo,
    getShelfGroupList
})
@withRouter
class ShoppingMallProductDetailPage extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            productInfo: null,
        }
        this.formRef = React.createRef()
    }

    componentDidMount () {
        const { productId } = getHistoryMatchParams(this.props)
        this.props.getShelfProductInfo({
            id: productId
        }, res => {
            const { prod_info } = res
            this.setState({
                productInfo: {
                    id: res.id,
                    customName: res.custom_name || prod_info.name,
                    groupIds: res.groups.map(group => group.id),
                    skus: res.skus.length ? res.skus : prod_info.skus.map(item => ({
                        id: item.id,
                        custom_price: item.price
                    })),
                    status: res.status,
                },
                productPreviewInfo: prod_info
            })
        })
        this.props.getShelfGroupList()
    }

    cancelEdit () {
        const { history } = this.props
        history.goBack('/shopping-mall/product')
    }

    onFormItemChange (changedValues) {
        this.setState({
            productInfo: {
                ...this.state.productInfo,
                ...changedValues
            }
        })
    }

    handleSubmit () {
        this.formRef.current?.submit()
    }

    submitForm () {
        const { productInfo } = this.state
        this.props.editShelfProductInfo({
            ...productInfo
        }, () => this.cancelEdit())
    }

    validateSkuList (_, value) {
        return new Promise((resolve, reject) => {
            value.map(item => {
                if (!item.custom_price) {
                    return reject(new Error('价格未填写'))
                }
            })
            return resolve()
        });
    }

    revertName () {
        const { productPreviewInfo } = this.state
        this.setState({
            productInfo: {
                ...this.state.productInfo,
                customName: productPreviewInfo.name
            }
        })
    }

    render () {
        const { shelfGroupList } = this.props
        const { productInfo, productPreviewInfo } = this.state

        return productInfo ? (
            <div className="bilin-web">
                <PageBackHeader title="编辑商品" backUrl='/shopping-mall/product'/>
                <div className="bilin-web-body form-page with-footer product-detail-page">
                    <Form
                        ref={this.formRef}
                        name="shelf-product-edit"
                        labelCol={{ span: 4 }}
                        wrapperCol={{ span: 20 }}
                        fields={exchangeFormDataToFields(productInfo)}
                        onValuesChange={this.onFormItemChange.bind(this)}
                        requiredMark={false}
                        onFinish={this.submitForm.bind(this)}
                        scrollToFirstError={{
                            behavior: actions =>
                                actions.forEach(({ el, top, left }) => {
                                    el.scrollTop = top - 100
                                    el.scrollLeft = left
                                }),
                        }}
                    >
                        <div className="ft-16 pdt-36 pdb-36">基本信息</div>
                        <Form.Item
                            label='商品名称'
                            name='customName'
                            rules={[
                                { required: true, message: '请输入名称' },
                            ]}
                        >
                            <Input placeholder="请输入名称"
                                   suffix={(
                                       <span className="clr-green cur-poi" onClick={this.revertName.bind(this)}>重置</span>
                                   )}
                            />
                        </Form.Item>
                        <Form.Item
                            label='商品类目'
                            name='groupIds'
                            rules={[
                                { required: true, message: '请选择商品类目' },
                            ]}
                        >
                            <Select
                                mode="multiple"
                                allowClear
                            >
                                { shelfGroupList.map(group => (
                                    <Select.Option key={group.id} value={group.id}>{group.name}</Select.Option>
                                )) }
                            </Select>

                        </Form.Item>
                        <Form.Item
                            label='商品单位'
                        >
                            <span>{ productPreviewInfo.unit }</span>
                        </Form.Item>
                        <Form.Item
                            label='商品主图'
                        >
                            <div className="flex-vertical-center">
                                { productPreviewInfo.title_pics.length ? (
                                    productPreviewInfo.title_pics.map(pic => pic.includes('.mp4') ? (
                                        <video src={pic} className="mgr-12" style={{width: '90px', height: '90px'}}/>
                                    ) : (
                                        <img src={pic} alt="" style={{width: '90px', height: '90px'}}/>
                                    ))
                                ) : <img src={getCdnUrl()} alt="" style={{width: '90px', height: '90px'}}/> }
                            </div>
                        </Form.Item>
                        <div className="ft-16 pdb-36">售价信息</div>
                        <Form.Item
                            name='skus'
                            wrapperCol={{ span: 24 }}
                            rules={[
                                { validator: this.validateSkuList.bind(this),}
                            ]}
                        >
                            <ShoppingMallProductDetailStandardHandle productPreviewInfo={productPreviewInfo}/>
                        </Form.Item>
                        <div className="ft-16 pdb-36">商品详情</div>
                        <Form.Item
                            label='图文描述'
                        >
                            <>
                                <div>{ productPreviewInfo.detail_description || '暂无' }</div>
                                { productPreviewInfo.detail_pics.map(pic => (
                                    <div>
                                        <img src={pic} alt="" style={{width: '344px', height: '344px'}}/>
                                    </div>
                                )) }
                            </>
                        </Form.Item>
                    </Form>
                </div>
                <div className="bilin-web-footer">
                    <Button onClick={this.cancelEdit.bind(this)}>取消</Button>
                    <Button type="primary" onClick={this.handleSubmit.bind(this)}>保存</Button>
                </div>
            </div>
        ) : null
    }
}

export default ShoppingMallProductDetailPage